<?php
class GroupsController extends Zend_Controller_Action
{
    public function init()
    {
    }

    /**
     * @param Model_Group $group
     * @return Form_Group 
     */
    protected function _form(Model_Group $group = null)
    {
        $form = new Form_Group($this->view->authMember, $group);
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $form->save();
                $this->_helper->messenger->success('group_has_been_created');
                $this->_redirect('/');
            } else {
                $this->_helper->messenger->error('group_not_created');
            }
        } elseif ($group) {
            $form->populate($group->toArray());
        }
        return $form;
    }

    public function indexAction()
    {
        $this->view->paginator = new Zend_Paginator(
            Ext_App::getTable('Model_DbTable_Group')->fetchPaginatorAdapter()
        );
        $this->view->paginator->setCurrentPageNumber($this->_getParam('page', 1));
        $this->view->paginator->setItemCountPerPage(Ext_App::getSetting('limits.groups_per_page'));
        $this->view->paginator->setPageRange(Ext_App::getSetting('limits.page_range'));
    }

    public function createAction()
    {
        $this->view->form = $this->_form();
    }

    public function editAction()
    {
        if (null == ($group = Ext_App::getTable('Model_DbTable_Group')->findById($this->_getParam('id')))) {
            $this->_helper->error->notFound();
        }
        if ($group->creator_id != $this->view->authMember->id) {
            $this->_helper->error->noPermissions();
        }
        $this->view->form = $this->_form($group);
    }

    public function profileAction()
    {
        if (null == ($this->view->group = Ext_App::getTable('Model_DbTable_Group')->findById($this->_getParam('id')))) {
            $this->_helper->error->notFound();
        }
    }
}

